import { getDetailsByIdApi } from "@/api/client/documentManagement/waybillManagement";
import { getListApi } from "@/api/configCenter/material";
import { reactive, ref } from "vue";

export default function InitHook() {
  const formDataRef = ref<any>(null);
  const loading = ref<boolean>(false);
  const formState = reactive<Partial<ClientWaybillManagement.MakeInvoice>>({
    id: "",
    waybillNum: "",
    materialQualityId: [],
    addressType: "AMAZON",
    warehouseCode: "",
    countryRegionName: "",
    channelName: "",
    remark: "",
    declarationTypeList: [],
    taxesTypeList: [],
    bizPreOrderShipmentFileResDtoList: [],
    preOrderShipmentBox: [],
    city: "",
    state: "",
    zipCode: "",
    receiverName: "",
    receiverEmail: "",
    receiverPhone: "",
    receiverCompany: "",
    address: "",
    addressTwo: "",
    addressThree: "",
    invoicementRemark: "",
    customsDeclarationType: "",
    customsTaxesType: "",
    customsClearanceType: "",
    vatTaxNumber: ""
  });
  const waybillInfo = ref<ClientWaybillManagement.WaybillDetails>({
    waybillNum: "",
    countryRegionName: "",
    channelName: "",
    remark: "",
    declarationTypeList: [],
    taxesTypeList: [],
    bizPreOrderShipmentFileResDtoList: [],
    preOrderShipmentBox: []
  });
  const materialOpts = ref<Array<Base.GeneraDataType>>([]);
  const conifg = {
    beforeChange: (changes: any) => {
      // [[row, prop, oldVal, newVal], ...]
      for (let i = 0; i < changes.length; i++) {
        const target = changes[i];
        if (["productDeclarePriceAll", "productDeclareNum", "productDeclarePrice", "pickingBoxWeight", "pickingBoxLength", "pickingBoxWidth", "pickingBoxHeight", "volumeWeight"].includes(target[1])) {
          if (isNaN(Number(target[3]))) {
            changes[i][3] = 0;
          }
        }
      }
    },
    afterChange: (changes: any) => {
      if (!changes) return;
      for (let i = 0; i < changes.length; i++) {
        const target = changes[i];
        if (["productDeclareNum", "productDeclarePrice"].includes(target[1])) {
          const scource = (formState.preOrderShipmentBox as any)[target[0]];
          const a = scource.productDeclareNum ? Number(scource.productDeclareNum) : 0;
          const b = scource.productDeclarePrice ? Number(scource.productDeclarePrice) : 0;
          scource.productDeclarePriceAll = a * b;
          formState.preOrderShipmentBox = JSON.parse(JSON.stringify(formState.preOrderShipmentBox));
        }
        if (["productDeclarePriceAll", "productDeclareNum", "productDeclarePrice"].includes(target[1])) {
          const declaredValueList = formState.preOrderShipmentBox?.map((t: ClientWaybillManagement.WaybillBox) => t.productDeclarePriceAll || 0) || [];
          formState.declaredValue = declaredValueList.reduce((a: number, b: number) => {
            return Number(a) + Number(b);
          });
        }
      }
    }
  };
  const dialogOpts = reactive<Base.DialogOpts>({
    title: "上传发票",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  const drawerOpts = reactive<Base.DrawerOpts>({
    title: "选择仓库",
    width: "720px",
    type: 1,
    passData: {},
    component: "",
    visible: false
  });
  const getMasterialOpts = () => {
    return getListApi({ pageNum: 1, pageSize: 9999, status: 1 } as MaterialIndex.SearchForm).then((res: any) => {
      const { code, data } = res;
      if (code === 200) {
        materialOpts.value = data.records || [];
      }
    });
  };
  const init = (id: string) => {
    getMasterialOpts();
    loading.value = true;
    return getDetailsByIdApi(id)
      .then((res: any) => {
        const { code, data } = res;
        if (code === 200) {
          Object.assign(formState, data);
          Object.assign(waybillInfo.value, data);
          if (data.materialQualityId) {
            formState.materialQualityId = data.materialQualityId?.split(",");
          }
          // formState.materialQualityId = [];
          formState.addressType = String(data.addressType);
        }
      })
      .finally(() => (loading.value = false));
  };
  return {
    formDataRef,
    formState,
    loading,
    materialOpts,
    getMasterialOpts,
    init,
    dialogOpts,
    waybillInfo,
    drawerOpts,
    conifg
  };
}
